Categories
React Tips

React Tips — Hooks Equivalents to Class Lifecycle Methods, Dynamic Tags

Spread the love

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at some tips for writing better React apps.

Reference a Local Image in React

We can reference a local image with React by loading it as a module.

For instance, we can write:

<img src={require('./pic.jpeg')} />

or:

import pic from './pic.jpeg';

//...

`<img src={`pic`} />`

or:

const pic = require('./pic.jpeg');

//...

<img src={pic} />

Images can be loaded as modules with Webpack.

Scroll to the Top of the Page After Render

We can scroll to the top of the page after render by writing;

componentDidMount() {
  window.scrollTo(0, 0)
}

in a class component.

componentDidMount runs code when the component mounts.

window.scrollTo(0, 0) scrolls to the top of the page.

In a function component, we can write:

useEffect(() => {
  window.scrollTo(0, 0)
}, [])

to scroll to the top of the page.

useEffect with an empty array as the 2nd argument only runs when the component is mounted.

Why are Fragments in React Better than Container divs?

Fragments are a bit faster and has less memory usage since no extra DOM node is created.

Some CSS features like flexbox and grid have their own special parent-child relationship, so add a wrapper div will interfere with those layouts.

And less DOM elements means that there’re fewer elements to inspect.

We can make our code cleaner with:

render() {
  return (
    <>
      foo.
      <h2>A heading</h2>
      bar.
      <h2>heading</h2>
      baz.
    </>
  );
}

or:

render() {
  return (
    <React.Fragment>
      foo.
      <h2>A heading</h2>
      bar.
      <h2>heading</h2>
      baz.
    </React.Fragment>
  );
}

If we need to add the key prop, then we’ve to use the long-form.

Set Default Checked Value in Checkbox with React

We can set the default checked value in a checkbox with React by using the checked attribute.

For instance, we can write:

function Checkbox() {
  const [checked, setChecked] = React.useState(true);

  return (
    <label>
      <input type="checkbox"
        checked={checked}
        onChange={() => setChecked(!checked)}
      />
      check me
    </label>
  );
}

We called the useState hook with to set the initial value of the checked state.

And we use the setChecked function to set the checked state as we get the checked value.

onChange runs every time we check or uncheck a button, so we can pass a callback to that set the latest checked state.

With class components, we write:

class Checkbox extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checked: true,
    };
  }
  toggleChange = () => {
    this.setState({
      checked: !this.state.checked,
    });
  }
  render() {
    return (
      <label>
        <input type="checkbox"
          checked={this.state.checked}
          onChange={this.toggleChange}
        />
        check me
      </label>
    );
  }
}

We have a checkbox that also have the checked and onChange props set.

However, in the toggleChange method, we called setState to update the state instead of calling a state change function.

Use componentDidMount() in React Hooks

If we use React hooks, then we can’t use any of the component lifecycle hooks that are in class components.

Instead, we’ve to find their hooks equivalent.

The hooks equivalent of componentDidMount is the useEffect hook with an empty array as its 2nd argument.

For instance, instead of writing:

componentDidMount() {
  window.addEventListener('click', () => {})
}

componentWillUnmount() {
  window.removeEventListener('click', () => {})
}

in a class component.

We write:

useEffect(() => {
  window.addEventListener('click', () => {});

  return () => {
    window.removeEventListener('click', () => {})
  }
}, [])

componentDidMount is equivalent to the useEffect hook with an empty array.

And componentWillUnmount is equivalent to the callback we return in the useEffect callback.

Dynamic Tag Name in JSX and React

If we want to create an element with a dynamic tag name with React, we can use the React.createElement method.

For instance, we can write:

React.createElement(`h${this.props.level}`, null, 'Hello')

In a component, we can write:

import React from 'react';

function Heading({ level, children, ...props }) {
  return React.createElement(`h${level}`, null, children)
}

Heading.defaultProps = {
  level: '1',
};

We pass in the level prop to set the type of heading.

children has the content.

Then we can use it by writing:

<Heading level="1">foo bar</Heading>

Conclusion

We can use createElement to create elements with dynamic tags.

Also, we can reference local images with React.

Fragments are better than wrapper divs since they don’t render any extra elements.

There are hooks equivalents of class component lifecycle methods.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *